package com.example.service;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.*;

@Service
public class AIService {
    
    private static final String API_URL = "https://api.deepseek.com/chat/completions";
    private static final String API_KEY = "这里是ai请求的api接口，可以的话自己改个免费的ai";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 获取AI响应
     * @param userMessage 用户消息
     * @return AI响应内容
     * @throws Exception 处理过程中的异常
     */
    public String getAIResponse(String userMessage) throws Exception {
        System.out.println("\n=== 开始调用 AI 服务 ===");
        
        // 构建请求体
        Map<String, Object> requestBody = buildRequestBody(userMessage);
        
        // 发送请求并获取响应
        return sendRequestAndGetResponse(requestBody);
    }

    /**
     * 构建请求体
     * @param userMessage 用户消息
     * @return 构建好的请求体
     */
    private Map<String, Object> buildRequestBody(String userMessage) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat");
        requestBody.put("stream", false);
        
        List<Map<String, String>> messages = new ArrayList<>();
        messages.add(Map.of("role", "system", "content", "You are a helpful assistant."));
        
        String fullMessage = userMessage + getPromptByQuestionType(userMessage);
        System.out.println("\n完整的问题内容：");
        System.out.println(fullMessage);
        
        messages.add(Map.of("role", "user", "content", fullMessage));
        requestBody.put("messages", messages);
        
        return requestBody;
    }

    /**
     * 根据题目类型获取对应的提示词
     * @param userMessage 用户消息
     * @return 对应的提示词
     */
    private String getPromptByQuestionType(String userMessage) {
        if (userMessage.contains("类型：multiple")) {
            return "\n请直接返回选项内容，多个答案用逗号分隔，不要包含选项字母。例如：Axure,Photoshop";
        } else if (userMessage.contains("类型：fill")) {
            return "\n请直接返回填空的答案，不要包含其他解释。";
        } else if (userMessage.contains("类型：answer")) {
            return "\n请直接返回问题的解答，保持简洁明了。";
        } else if (userMessage.contains("类型：completion")) {
            return getCompletionPrompt(userMessage);
        } else if (userMessage.contains("类型：judgement")) {
            return "\n请直接返回'正确'或'错误'，不要包含其他解释。";
        } else {
            return "\n请直接返回选项答案，不要包含其他解释。";
        }
    }

    /**
     * 获取完成题的提示词
     * @param userMessage 用户消息
     * @return 完成题的提示词
     */
    private String getCompletionPrompt(String userMessage) {
        if (userMessage.contains("简述") || userMessage.contains("描述") || userMessage.contains("列举")) {
            return "\n请根据题目要求，给出详细的解答。";
        }
        return "\n请直接返回问题的解答，保持简洁明了。";
    }

    /**
     * 发送请求并获取响应
     * @param requestBody 请求体
     * @return AI响应内容
     * @throws Exception 处理过程中的异常
     */
    private String sendRequestAndGetResponse(Map<String, Object> requestBody) throws Exception {
        String jsonBody = objectMapper.writeValueAsString(requestBody);
        System.out.println("\n发送给 AI 的请求体：");
        System.out.println(jsonBody);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(API_URL);
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + API_KEY);
            httpPost.setEntity(new StringEntity(jsonBody, "UTF-8"));

            System.out.println("\n发送 HTTP 请求...");
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("\n收到 HTTP 响应，状态码: " + statusCode);
                
                return processResponse(response);
            }
        } catch (Exception e) {
            System.out.println("\n调用 AI 服务时出错：");
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 处理响应
     * @param response HTTP响应
     * @return AI响应内容
     * @throws Exception 处理过程中的异常
     */
    private String processResponse(CloseableHttpResponse response) throws Exception {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String responseBody = EntityUtils.toString(entity);
            System.out.println("\nAI 原始响应：");
            System.out.println(responseBody);
            
            Map<String, Object> responseMap = objectMapper.readValue(responseBody, Map.class);
            List<Map<String, Object>> choices = (List<Map<String, Object>>) responseMap.get("choices");
            if (choices != null && !choices.isEmpty()) {
                Map<String, Object> firstChoice = choices.get(0);
                Map<String, String> message = (Map<String, String>) firstChoice.get("message");
                String content = message.get("content");
                System.out.println("\n提取的答案：");
                System.out.println(content);
                return content;
            }
        }
        return "无法获取 AI 响应";
    }
} 